export class CustcareWs {
    wsUrl: string
    token: string | null
    instance: WebSocket
    timeout: number
    timeoutObj: any

    constructor(wsUrl: string, token: string) {
        this.timeout = 60000
        this.wsUrl = wsUrl
        this.token = token
        // 建立连接
        this.instance = new WebSocket(this.wsUrl + '/ws?token=' + this.token)
        // 连接成功
        this.instance.onopen = this.onOpen
        // 连接关闭
        this.instance.onclose = this.onClose
        // 接收信息
        this.instance.onmessage = this.onMessage

        this.heartBeat()
    }

    onOpen(e: Event) {
        console.log('websocket open ', e)
    }

    onClose(e: CloseEvent) {
        console.log('websocket close ', e)
        window.dispatchEvent(
            new CustomEvent('onCloseWS', {
                detail: {
                    data: e
                }
            })
        )
    }

    onMessage(e: MessageEvent) {
        window.dispatchEvent(
            new CustomEvent('onMessageWS', {
                detail: {
                    data: e.data
                }
            })
        )
    }

    sendMessage(objMsg: any) {
        // console.log('发送消息 readyState = ', this.instance?.readyState)
        if (this.instance == null || this.instance.readyState == 1) {
            // console.log('发送消息:', objMsg.content)
            this.instance?.send(JSON.stringify(objMsg))
            return true
        } else {
            return false
        }
    }

    heartBeat() {
        this.timeoutObj = setInterval(() => {
            console.log('心跳=', this.instance?.readyState)
            if (this.instance == null || this.instance.readyState != 1) {
                // 重新连接
                this.instance = new WebSocket(
                    this.wsUrl + '/ws?token=' + this.token
                )
                // 连接成功
                this.instance.onopen = this.onOpen
                // 连接关闭
                this.instance.onclose = this.onClose
                // 接收信息
                this.instance.onmessage = this.onMessage
            } else {
                // 发送心跳包
                window.dispatchEvent(new CustomEvent('onHeartBeatWs'))
            }
        }, this.timeout)
    }

    wsClose() {
        this.compulsoryLogout()
        this.instance?.close()
    }

    compulsoryLogout() {
        console.log('关闭心跳')
        clearInterval(this.timeoutObj)
    }
}
